<?php

namespace App\Services\Admin;

// use  App\Dao\Lsv\AdminDao;
use  App\Dao\Lsv\AdminDao\Orm as AdminDao;
use App\Utils\Nanoid\Control as Nanoid;
use App\Common\Http\Basics\Error;
use App\Common\Helper;

class Dev
{
    public static function reload()
    {
        $new_pass = Nanoid::create(20);
        (new AdminDao)->whereRoleId(-1)->reloadPass(
            [
                'password' => md5($new_pass),
                'dev_pwd' => $new_pass
            ]
        );
        return self::check();
    }

    public static function check()
    {
        $result = (new AdminDao)->whereRoleId(-1)->end()->first(['username', 'dev_pwd']);
        if (!$result) {
            $username = self::createUserName();
            $dev_pwd = Nanoid::create(20);
            $result = (new AdminDao)->add([
                'username' => $username,
                'password' => md5($dev_pwd),
                'role_id'  => -1,
                'nickName'  => "开发者",
                'realName'  => "",
                'status'  => 1,
                'phone'  => "",
                'dev_pwd'  => $dev_pwd,
            ]);
        }
        return ['username' => $result->username, 'password' => $result->dev_pwd];
    }

    private static function createUserName($num = 1)
    {
        if ($num >= 4) return Helper::toHttpEnum(Error::DEV_ACCOUNT_CREATE_FAIL);
        $nanoid = Nanoid::create(20);
        return (new AdminDao)->whereUserName($nanoid)->end()->exists() ? self::createUserName(++$num) : $nanoid;
    }
}
